import * as vscode from 'vscode'

export class AgentWebviewProvider implements vscode.WebviewViewProvider {
    private webview: vscode.Webview | undefined
    constructor(private readonly context: vscode.ExtensionContext) { }
    resolveWebviewView(webviewView: vscode.WebviewView,
        context: vscode.WebviewViewResolveContext,
        token: vscode.CancellationToken): Thenable<void> | void {
        // 保存当前渲染的webview实例
        this.webview = webviewView.webview
        // 获取打包后的js和css的文件路径
        const scriptUri = webviewView.webview.asWebviewUri(
            vscode.Uri.joinPath(
                this.context.extensionUri,
                "agent-webview",
                "dist",
                "assets",
                "index.js"
            )
        )

        const cssUri = webviewView.webview.asWebviewUri(
            vscode.Uri.joinPath(
                this.context.extensionUri,
                "agent-webview",
                "dist",
                "assets",
                "index.css"
            )
        )

        // 设置允许使用js
        webviewView.webview.options = {
            enableScripts: true
        }
        webviewView.webview.html = `
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script type="module" crossorigin src=${scriptUri}></script>
    <link rel="stylesheet" crossorigin href=${cssUri}>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>
`

        // 监听前端发来的信息
        webviewView.webview.onDidReceiveMessage(async (message: string) => {
            vscode.window.showInformationMessage(message)
        })
    }

    postMessage(message: string) {
        // 使用webview传递信息给前端
        this.webview?.postMessage(message)
    }

}